package week5.day33;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author fengzihao
 * @Date 2024-05-17 18:59
 */
public class GoodCharCount {
    public static void main(String[] args) {
        String[] words = new String[]{"cat", "bt", "hat", "tree"};
        String chars = "atach";
        int count = 0;
        Map<Character, Integer> mapByChars = getMapByString(chars);
        for (String word : words) {
            Map<Character, Integer> mapByWord = getMapByString(word);
            Set<Map.Entry<Character, Integer>> wordEntries = mapByWord.entrySet();
            // Set<Map.Entry<Character, Integer>> charsEntries = mapByChars.entrySet();
            boolean flag = true;
            for (Map.Entry<Character, Integer> wordEntry : wordEntries) {
                Character key = wordEntry.getKey();
                Integer value = wordEntry.getValue();
                if (!mapByChars.containsKey(key) ||mapByChars.get(key)<value)
                    flag = false;
            }
            if (flag)
                count+=word.length();
        }
        System.out.println("count = " + count);
    }

    private static Map<Character, Integer> getMapByString(String str) {
        char[] charArray = str.toCharArray();
        Map<Character, Integer> returnMap = new HashMap<>();
        for (char c : charArray) {
            returnMap.put(c, returnMap.getOrDefault(c, 0) + 1);
        }
        return returnMap;
    }
}
